<template>
    <div>
        <el-form :inline="true" :model="condition" class="search-form" label-width="120px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="作业港口">
                        <select-port :name="portName" v-model="condition['search_EQ_portCode']"></select-port>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="放行时间起">
                        <el-date-picker v-model="condition['search_GTE_passTime']"
                                        :picker-options="startPickerOptions" type="date" placeholder="起始日期"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>

                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="放行时间止">
                        <el-date-picker v-model="condition['search_LTE_passTime']" @change="handleChangeEnd"
                                        :picker-options="endPickerOptions" type="date" placeholder="结束日期"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="箱号">
                        <el-input v-model.trim="condition['search_LIKE_containerId']" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="航次">
                        <el-input v-model.trim="condition['search_LIKE_voyage']" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="船名">
                        <el-input v-model.trim="condition['search_LIKE_shipName']" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="提单号">
                        <el-input v-model.trim="condition['search_LIKE_billNumber']" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="放行类型">
                        <el-select v-model="condition['search_EQ_devanType']" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictReleaseType" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结算单位">
                        <auto-search-custom
                            @selectName="v=>condition['search_LIKE_accountUnit']=v" :isShipAgent="true" ></auto-search-custom>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结算方式">
                        <el-select v-model="condition['search_EQ_accountWay']" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictSettlementType" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="尺寸">
                        <el-select v-model="condition['search_EQ_containerSize']" placeholder="请选择" clearable>
                            <el-option v-for="item in sizeList" :key="item.containerSize" :label="item.containerSize" :value="item.containerSize">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-button type="primary" class="ml-120" @click="loadData">查 询</el-button>
                    <el-button @click="handleExport">导出Excel</el-button>
                    <el-button @click="handleChange(true)" v-if="power('TALLY_WORK_DEVANPASSLIST:UPD')">调整付费单位</el-button>
                    <el-button @click="handleChange(false)" v-if="power('TALLY_WORK_DEVANPASSLIST:UPD')">调整放行类型</el-button>
                    <el-button @click="handleFeeForm" v-if="power('TALLY_WORK_DEVANPASSLIST:PASS')">拆提放行</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-row type="flex" justify="end" class="mt-10 ">
            <el-col :span="8">
                <el-tag size="medium">
                    {{ selectTitle }}
                </el-tag>
            </el-col>
            <el-col :span="16" style="display: flex;justify-content: space-between">
                <title-point color="#30C8CA">
                    <div slot="content">
                        总箱量 :
                        <span style="font-size: 16px">{{ list.length }}</span>
                    </div>
                </title-point>
                <title-point color="#449DFF">
                    <div slot="content">
                        现结箱量 :
                        <span style="font-size: 16px">{{ nowNum }}</span></div>
                </title-point>
                <title-point color="#50B155">
                    <div slot="content">
                        月结箱量 :
                        <span style="font-size: 16px">{{ monthNum }}</span></div>
                </title-point>
            </el-col>
        </el-row>
        <el-table :data="list" border stripe max-height="500" class="mt-10" @selection-change="handleSelectionChange">
            <el-table-column fixed="left" type="selection" prop="id" width="55"></el-table-column>
            <el-table-column type="index" label="序号" fixed="left"  width="55"></el-table-column>
            <el-table-column prop="devanType" label="放行类型"  min-width="110">
                <template slot-scope="scope">
                    {{ scope.row.devanType | _filterReleaseType }}
                </template>
            </el-table-column>
            <el-table-column prop="portName" label="作业港口"  min-width="110"></el-table-column>
            <el-table-column prop="passTime" label="放行日期"  min-width="120">
                <template slot-scope="scope">
                    {{ scope.row.passTime | filterDate }}
                </template>
            </el-table-column>
            <el-table-column prop="shipName" label="船名"  min-width="80"></el-table-column>
            <el-table-column prop="voyage" label="航次"  min-width="90"></el-table-column>
            <el-table-column prop="containerId" label="箱号"  min-width="140"></el-table-column>
            <el-table-column prop="billNumber" label="提单号"  min-width="140"></el-table-column>
            <el-table-column prop="containerType" label="箱型"  min-width="80"></el-table-column>
            <el-table-column prop="containerSize" label="尺寸"  min-width="80"></el-table-column>
            <el-table-column prop="ef" label="空重"  min-width="80">
                <template slot-scope="scope">
                    {{ scope.row.ef | _filterIfHeavyType }}
                </template>
            </el-table-column>
            <el-table-column prop="cargoName" label="货名"  min-width="90"></el-table-column>
            <el-table-column prop="cargoCount" label="件数"  min-width="80"></el-table-column>
            <el-table-column prop="accountWay" label="结算方式" align="center"  min-width="110">
                <template slot-scope="scope">
                    <div v-bg="scope.row.accountWay">
                        {{ scope.row.accountWay | _filterSettlementType }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="accountUnit" label="结算单位"  min-width="120"></el-table-column>
            <el-table-column prop="passUser" label="放行人"  min-width="120"></el-table-column>
            <el-table-column prop="passTime" label="放行时间"  min-width="120"></el-table-column>
            <el-table-column fixed="right" align="center" label="操作"  width="120">
                <template slot-scope="scope">
                    <el-button size="small" type="text" @click="handleEdit(scope.row)" v-if="power('TALLY_WORK_DEVANPASSLIST:CANCEL')">撤销放行</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row class="bottom mt-10" type="flex" justify="space-between" v-show="total>0">
            <div class="oper">

            </div>
            <el-pagination class="page" @size-change="size=>pageInfo.iDisplayLength=size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :current-page.sync="pageInfo.pageStart" :page-sizes="pageInfo.pageArr"
                           :page-size="pageInfo.iDisplayLength" :total="total">
            </el-pagination>
        </el-row>
        <el-dialog title="现结撤销放行" :visible.sync="dialogForm" width="400px">
            <el-form :model="cForm" label-width="100px">
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="箱号：">
                            {{ cForm.containerId }}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="退款金额：">
                            <el-input-number style="width: 188px" :controls="false" v-model="cForm.accountFee"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="撤销备注：" prop="remark">
                            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="cForm.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogForm = false">取 消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="$store.getters.loadingBtn">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="调整付费单位" :visible.sync="dialogUnit" width="400px">
            <el-row type="flex" justify="center" class="mt-20">
                <auto-search-custom v-if="dialogUnit" @selectName="v=>payUnit=v" :isShipAgent="true" :isSpecialForm="true"></auto-search-custom>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogUnit = false">取 消</el-button>
                <el-button type="primary" @click="handleChangeUnit" :loading="$store.getters.loadingBtn">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="调整放行类型" :visible.sync="dialogType" width="400px">
            <el-form :inline="true"  class="search-form" label-width="120px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="放行类型：">
                            <el-select v-model="devanForm.devanType" placeholder="请选择" @change="changeDevanTypeForm">
                                <el-option v-for="[key, val] in _dictReleaseType" :key="key" :label="val" :value="key">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="费用名称：">
                            <span>拆箱费用</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="devanForm.devanType == 'C'">
                    <el-col :span="24">
                        <el-form-item label="结算方式：">
                            <el-select v-model="devanForm.accountWay" placeholder="请选择" @change="changeDevanTypeForm">
                                <el-option v-for="[key, val] in _dictSettlementType" :key="key" :label="val" :value="key">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="devanForm.devanType == 'C'">
                    <el-col :span="24">
                        <el-form-item label="结算单位：">
                            <auto-search-custom @selectName="v=>devanForm.accountUnit=v" :isShipAgent="true" @change="changeDevanTypeForm"></auto-search-custom>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="devanForm.devanType == 'C'">
                    <el-col :span="24">
                        <el-form-item label="备注：">
                            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="devanForm.remark" style="width: 190px;"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="devanForm.devanType != ''">
                    <el-col :span="24">
                        <el-form-item :label="devanForm.devanType == 'T' ? '退款金额：':'补收金额：'">
                            <span :style="devanForm.devanType == 'T' ? 'color:green' : 'color:red'">{{(devanForm.devanType == 'T' && Number(devanForm.money) > 0) ? '-' :''}}{{devanForm.money==""?'0':devanForm.money}}元</span>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogType = false">取 消</el-button>
                <el-button type="primary" @click="handleChangeType" :loading="$store.getters.loadingBtn">确 定</el-button>
            </span>
        </el-dialog>
        <fee-form v-if="feeForm" ref="feeForm" @load="loadData"></fee-form>
    </div>
</template>

<script>
    import autoSearchEntrust from '@/components/autocomplete/autoSearchEntrust'
    import autoSearchSize from '@/components/autocomplete/autoSearchSize'
    import autoSearchCustom from '@/components/autocomplete/autoSearchCustom'
    import { getContainerSizeList } from '@/api/planList/planList.js'
    import autoSearchPortStation from '@/components/autocomplete/autoSearchPortStation'
    import {
        getFeeCloseRecord,
        getFeeCloseCancelM,
        feeCloseCancelC,
        changeDevanType,
        changePayUnit,
        releaseCount,
        getCashMoney,
        releaseCountCX
    } from '@/api/shipPlan/shipPlan.js'
    import feeForm from './feeForm'
    import titlePoint from '../common/title-point'
    import selectPort from '@/components/select/selectPort'
    import { newExportExcel } from "@/utils/newExport";
    import { ifHeavyType,settlementType,releaseType, portCode } from "../../../assets/dict";
    export default {
        name: "feeForm",
        components: {
            selectPort, autoSearchEntrust, autoSearchSize, autoSearchCustom, feeForm, titlePoint
        },
        data() {
            return {
                condition: {},
                cForm: {},
                list: [],
                selectTable: [],
                total: 0,
                pageInfo: this.$defalutPage(),
                listLoading: false,
                dialogForm: false,
                mDialog: false,
                feeForm: false,
                dialogUnit: false,
                payUnit: '',
                dialogType: false,
                devanType: '',
                totalNum: 0,
                nowNum: 0,
                monthNum: 0,
                portName:'',
                sizeList:'',
                devanForm:{
                    devanType : '',
                    accountWay : '',
                    accountUnit : '',
                    remark:'',
                    money:''
                }
            }
        },
        directives: {
            bg: {
                inserted(el, binding) {
                    if (binding.value === 'M') {
                        el.parentNode.parentNode.style.backgroundColor = '#9900FF'
                    } else if (binding.value === 'C') {
                        el.parentNode.parentNode.style.backgroundColor = '#cc0099'
                    }
                    el.style.color = '#ffffff'
                },
                update(el,binding){
                    if (binding.value === 'M') {
                        el.parentNode.parentNode.style.backgroundColor = '#9900FF'
                    } else if (binding.value === 'C') {
                        el.parentNode.parentNode.style.backgroundColor = '#cc0099'
                    }
                    el.style.color = '#ffffff'
                }
            }
        },
        mounted() {
            // this.loadData()
            const condition = JSON.parse(sessionStorage.getItem('shipIndex'))
            this.condition = { ...condition }
            const SHIP_DATE = sessionStorage.getItem('SHIP_DATE')
            this.portName = portCode.get(this.condition.search_EQ_portCode)
            this.loadData()
            if (SHIP_DATE) {
                // this.condition['search_GTE_createDateTime'] = SHIP_DATE + ' 00:00:00'
                // this.condition['search_LTE_createDateTime'] = SHIP_DATE + ' 23:59:59'
                this.$set(this.condition, 'search_GTE_passTime', SHIP_DATE + ' 00:00:00')
                this.$set(this.condition, 'search_LTE_passTime', SHIP_DATE + ' 23:59:59')
            }
            this.loadSize();
        },
        activated() {
            this.loadData()
        },
        methods: {
            loadData() {
                this.listLoading = true
                console.log(this.condition)
                if(sessionStorage.getItem('ContainerId')) {
                    this.condition.search_LIKE_containerId = sessionStorage.getItem('ContainerId')
                    
                }else{
                    if(!this.condition.search_LIKE_containerId) {
                        this.condition.search_LIKE_containerId = ''  
                    } 
                }
                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = this.pageInfo.iDisplayLength
                params.sortType = '-createDateTime'
                params.search_EQ_type = 'ZX'
                getFeeCloseRecord(params).then(res => {
                    const data = res.data
                    this.total = data.iTotalRecords
                    this.listLoading = false
                    this.list = data.aaData
                    this.totalNum = this.list.length
                    this.monthNum = 0
                    this.nowNum = 0
                    this.list.forEach(f => {
                        if (f.accountWay === 'M') {
                            this.monthNum = this.monthNum + 1
                        }
                        if (f.accountWay === 'C') {
                            this.nowNum = this.nowNum + 1
                        }
                    })
                })
            },
            loadSize(){
                getContainerSizeList().then(res => {
                    this.sizeList = res.data.aaData
                })
            },
            handleEdit(item) {
                if (item.accountWay === 'C') {
                    let data = [{
                        id: item.tallyDetailId,
                        accountUnit: item.accountUnit,
                        accountWay: item.accountWay
                    }]
                    releaseCount(data).then(res => {
                        this.dialogForm = true
                        this.cForm.accountFee = res.data
                        this.cForm.containerId = item.containerId
                        this.cForm.remark = `箱号【${item.containerId}】现结拆提放行撤销。`
                        this.cForm.id = item.tallyDetailId
                        this.cForm.recordId = item.recordId
                        this.cForm.accountUnit = item.accountUnit
                        this.cForm.accountWay = item.accountWay
                    })
                } else {
                    const msg = `箱号【${item.containerId}】是否确认撤销放行`
                    this.$confirm(msg, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        iconClass: 'el-icon-question'
                    }).then(() => {
                        let data = {
                            id: item.tallyDetailId,
                            recordId: item.recordId,
                            accountUnit: item.accountUnit,
                            accountWay: item.accountWay,
                        }
                        getFeeCloseCancelM(data).then(res => {
                            this.$message({ type: 'success', message: '撤销成功!' });
                            this.loadData()
                        })
                    })
                }
            },
            handleSubmit() {
                feeCloseCancelC(this.cForm).then(res => {
                    this.dialogForm=false
                    this.$message({ type: 'success', message: '撤销成功!' });
                    this.loadData()
                })
            },
            handleChangeEnd(val) {
                let setVal = val;
                if (val) {
                    setVal = val.split(" ")[0] + " 23:59:59";
                }
                this.condition["search_LTE_passTime"] = setVal;
            },
            handleSelectionChange(val) {
                this.selectTable = val
            },
            handleFeeForm() {
                this.$router.push({ path: '/work/shipPlan/feeForm',name: '拆提放行'})
                // this.feeForm = true
                // this.$nextTick(() => {
                //     this.$refs.feeForm.dialogForm = true
                // })
            },
            handleChange(bool) {
                if (this.selectTable.length === 0) {
                    this.$message({ message: '请先选择数据!', type: 'error' })
                    return
                }
                if (bool) {
                    this.dialogUnit = true
                } else {
                    this.devanForm={
                            devanType : '',
                            accountWay : '',
                            accountUnit : '',
                            remark:'',
                            money:''
                    }
                    this.dialogType = true
                }
            },
            changeDevanTypeForm(){
                let data = []
                for (let i = 0; i < this.selectTable.length; i++) {
                    const el = this.list[i]
                    data.push({
                        tallyDetailId: el.tallyDetailId,
                        accountUnit: this.devanForm.accountUnit,
                        accountWay: this.devanForm.accountWay,
                    })
                }
                let dataOne = []
                for (let i = 0; i < this.selectTable.length; i++) {
                    const el = this.list[i]
                    dataOne.push({
                        id: el.tallyDetailId,
                        accountUnit: this.devanForm.accountUnit,
                        accountWay: this.devanForm.accountWay,
                    })
                }
                if (this.devanForm.devanType == 'T'){
                    getCashMoney(data).then(res => {
                        this.devanForm.money = res.data
                    })
                } else {
                    if (this.devanForm.devanType != "" && this.devanForm.accountUnit != "" && this.devanForm.accountWay != "" ){
                        if (this.devanForm.accountWay == 'M'){
                            this.devanForm.money = ""
                        } else {
                            let total = ""
                            let cashMoney = ""
                            getCashMoney(data).then(res => {
                                cashMoney = res.data
                                releaseCountCX(dataOne).then(res => {
                                    total = res.data
                                    this.devanForm.money = (Number(total) - Number(cashMoney)).toFixed(2)
                                })
                            })
                        }
                    } else {
                        this.devanForm.money = ""
                    }
                }

            },
            handleChangeUnit() {
                let arr = []
                for (let i = 0; i < this.selectTable.length; i++) {
                    const el = this.selectTable[i]
                    arr.push({
                        id: el.tallyDetailId,
                        accountUnit: this.payUnit
                    })
                }
                changePayUnit(arr).then(res => {
                    this.$message({ message: '调整成功!', type: 'success' })
                    this.dialogUnit = false
                    this.loadData()
                })
            },
            handleChangeType() {
                let arr = []
                for (let i = 0; i < this.selectTable.length; i++) {
                    const el = this.selectTable[i]
                    if (this.devanForm.devanType == 'T'){
                        arr.push({
                            tallyDetailId : el.tallyDetailId,
                            recordId: el.recordId,
                            devanType: this.devanForm.devanType,
                            cxAccountFee: this.devanForm.money
                        })
                    } else {
                        arr.push({
                            tallyDetailId : el.tallyDetailId,
                            recordId: el.recordId,
                            devanType: this.devanForm.devanType,
                            cxAccountFee: this.devanForm.money,
                            cxRemark : this.devanForm.remark,
                            cxAccountUnit: this.devanForm.accountUnit,
                            cxAccountWay : this.devanForm.accountWay
                        })
                    }
                }
                changeDevanType(arr).then(res => {
                    this.$message({ message: '调整成功!', type: 'success' })
                    this.dialogType = false
                    this.loadData()
                })
            },
            handleExport() {
                let map = new Map();
               map.set('devanType','放行类型')
               map.set('portName','作业港口')
               map.set('passTime','放行日期')
               map.set('shipName','船名')
               map.set('voyage','航次')
               map.set('containerId','箱号')
               map.set('containerType','箱型')
               map.set('containerSize','尺寸')
               map.set('ef','空重')
               map.set('cargoName','货名')
               map.set('cargoCount','件数')
               map.set('accountWay','结算方式')
               map.set('accountUnit','结算单位')
               map.set('passUser','放行人')
               map.set('passTime','放行时间')

                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = 9999
                params.sortType = '-createDateTime'
                params.search_EQ_planType = 'ZX'
                getFeeCloseRecord(params).then(res => {
                    let exportRecords = [];
                    let exportArr = res.data.aaData;
                    exportArr.forEach(record => {
                        let exportRecord = {};
                        for (let [key, value] of map.entries()) {
                            if(key==='devanType'){
                                record[key] = releaseType.get(record[key]);
                            }
                            if (key === "ef") {
                                record[key] = ifHeavyType.get(record[key]);
                            }
                            if (key === "accountWay") {
                                record[key] = settlementType.get(record[key]);
                            }exportRecord[value] = record[key];
                        }
                        exportRecords.push(exportRecord);
                    });
                    newExportExcel("拆提放行", exportRecords);
                })
            }

        },
        watch: {
            pageInfo: {
                deep: true,
                handler: function () {
                    this.loadData()
                }
            },
            dialogUnit(bool) {
                if (!bool) {
                    this.payUnit = ''
                }
            },
            dialogType(bool) {
                if (!bool) {
                    this.devanType = ''
                }
            }
        },
        computed: {
            startPickerOptions() {
                let endDate = this.condition["search_LTE_passTime"];
                return {
                    disabledDate(time) {
                        if (endDate) {
                            return time.getTime() > new Date(endDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
            endPickerOptions() {
                let startDate = this.condition["search_GTE_passTime"];
                return {
                    disabledDate(time) {
                        if (startDate) {
                            return time.getTime() < new Date(startDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
            selectTitle() {
                if (this.selectTable.length === 0) {
                    return '未选择'
                } else {
                    return '已选择 ' + this.selectTable.length + ' 条数据'
                }
            }
        },
        filters: {
            filterDate(val) {
                return val ? val.substr(0, 10) : '-'
            }
        }
    }
</script>

<style scoped>
    .bottom {
        display: flex;
        padding: 0 10px;
        justify-content: space-between;
        align-items: center;
    }

    .operbar {
        padding-top: 10px;
        display: flex;
        justify-content: flex-end;
    }
</style>
